package com.ngrok;

import com.ngrok.client.NgrokClient;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;

/**
 * Created by pj on 2017/10/9.
 */
public class NgrokContext {

    private final static Map<String,String> idmap=new HashMap<String,String>();
    private NgrokClient ngrokClient;

    private NgrokClient localhost;

    private Channel remotechannel;

    private NgrokConfig config;

    private final static char[] chars="ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz".toCharArray();

    public NgrokContext(NgrokClient ngrokClient,NgrokConfig config){
        this.ngrokClient=ngrokClient;
        this.localhost=localhost;
        this.config=config;
    }


    public Channel getRemotechannel() {
        return remotechannel;
    }

    public void close(Channel channel){
        if(channel!=null&&channel.isOpen() && channel.isWritable() ){
            channel.disconnect().addListener(future->{
                if(future.isSuccess()){
                    System.out.println("关闭成功");
                }
                    Throwable cause = future.cause();
                    if (cause != null) {
                        System.out.println(cause.getMessage());
                    }
            });
        }
    }

    public Channel getNewChannel(String host,int prot) {

        return ngrokClient.connect(host,prot);
    }

    public String getChars() {

        return sample(chars,8);
    }

    public void execute(Runnable runnable){
        this.ngrokClient.getGroup().execute(runnable);
    }

    public String sample(char[] chars,int limit){
        Random random=new Random();
        StringBuilder builder=new StringBuilder("");
        random.ints(0, chars.length).limit(8).forEach(i->{
            builder.append(chars[i]);
        });
        return builder.toString();
    }
    public void init(){
        this.ngrokClient.init();
    }


    public Channel getNewChannel(String key ,String host,int prot) {
        return ngrokClient.connect(key,host,prot);
    }

    public NgrokConfig getConfig() {
        return config;
    }

    public void setConfig(NgrokConfig config) {
        this.config = config;
    }

    public void setRemotechannel(Channel remotechannel) {
        this.remotechannel = remotechannel;
    }

    public Channel getLocalhost(String host,int prot){
        return ngrokClient.localhost.connect(host,prot);
    }

    public  void addClientId(String key, String id){
        idmap.put(key,id);
    }

    public String getClientid(String key){
        return idmap.get(key);
    }
}
